// Init.hpp
#pragma once

#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include "log.hpp"

const std::string dictname = "./dict.txt";
const std::string sep = ":";

// red:红色
static bool Split(std::string &s, std::string *p1, std::string *p2)
{
    size_t pos = s.find(sep);
    if (pos == std::string::npos) return false;

    // string substr (size_t pos = 0, size_t len = npos) const;
    *p1 = s.substr(0, pos);  // 第二个参数表示要截取字符的个数，不是下标
    *p2 = s.substr(pos+1);  // 第二个参数缺省值是std::string::npos，表示截到结尾

    return true;
}

class Init
{
public:
    Init()
    {
        std::ifstream in(dictname);  // 构建一个标准输入流，这个文件就默认被打开了
        if (!in.is_open())
        {
            lg(Fatal, "ifstream open %s error", dictname.c_str());
            exit(1);
        }
        std::string line;
        // istream& getline (istream& is, string& str);
        while (std::getline(in, line))
        {
            std::string part1, part2;
            Split(line, &part1, &part2);
            dict.insert({part1, part2});
        }

        in.close();
    }
    std::string translation(const std::string &key)
    {
        auto iter = dict.find(key);
        if (iter == dict.end()) return "Unknown";
        else return iter->second;
    }
private:
    std::unordered_map<std::string, std::string> dict;
};